import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {Router} from "@angular/router";
import {WsService} from "../../service/ws.service";
import {ProtocolCmds, WsProtocol} from "../../model/WsProtocol";

type DataType = 'info' | 'send' | 'receive';

@Component({
  selector: 'app-windows',
  templateUrl: './windows.component.html',
  styleUrls: ['./windows.component.scss']
})
export class WindowsComponent implements OnInit, AfterViewInit {
  @ViewChild("scrollContent", {static: true}) screenEl: ElementRef;
  dataList: Array<{ type: DataType, content: string }> = [];
  cmd: string = '';

  constructor(private router: Router, private wsService: WsService) {
  }

  ngOnInit() {
  }

  ngAfterViewInit(): void {
    this.appendData('info', '正在连接服务器...');
    this.wsService
      .onOpen(() => this.appendData('info', '服务器连接成功'))
      .onClose(() => this.appendData('info', '链接已经关闭!'))
      .onError(ev => this.appendData('info', `链接出现异常: ${ev.getMessages()}`))
      .onMessage(ev => {
        let data = <WsProtocol>JSON.parse(ev.data);
        if (data.e) this.appendData("receive", data.es);
        else {
          let content = (data.d + '').replace(/</g, '&lt;').replace(/\n/g, '<br/>');
          this.appendData("receive", content);
        }
      }).init("ws://127.0.0.1/ws");
  }

  private appendData(type: DataType, content: string) {
    this.dataList.push({type: type, content: content});
    while (100 < this.dataList.length)
      this.dataList.pop();

    setTimeout(() => {
      this.screenEl.nativeElement.scrollTop = this.screenEl.nativeElement.scrollHeight + 100;
    }, 1000);
  }

  // 发送指令
  sendCmd() {
    if (!this.cmd.length) return;
    this.cmd = this.cmd.trim();

    let p = <WsProtocol>{m: ProtocolCmds.modules.terminal.m, b: ProtocolCmds.modules.terminal.b.send, d: this.cmd};
    this.wsService.send(JSON.stringify(p));
    this.cmd = '';
  }
}
